from django import template
from django.db.models import Count
from django.db.models.functions import TruncMonth

from appdemo.models import *

register = template.Library()


@register.inclusion_tag('left_menu.html')
def left_menu(username):
    user_obj = UserInfo.objects.filter(username=username).first()
    blog = user_obj.blog
    # 1. 查询当前用户的所有分类以及分类下的文章数
    category_list = (Category.objects.filter(blog=blog).
                     annotate(count_num=Count('article')).values_list('name', 'count_num', 'pk'))
    # 2. 查询当前用户的所有标签以及标签下的文章数
    tag_list = (Tag.objects.filter(blog=blog).
                annotate(count_num=Count('article')).values_list('name', 'count_num', 'pk'))
    # 3. 不同月份的文章进行统计
    # annotate(month=TruncMonth('create_time')):将日期中的月份生成新的字段叫做month
    date_list = ((Article.objects.filter(blog=blog).
                  annotate(month=TruncMonth('create_time')).  # 生成新的字段month(某年某月)
                  values('month').annotate(count_num=Count('pk'))).
                 values_list('month', 'count_num'))
    print("left_menu", tag_list)
    return locals()
